

import 'dart:io';

import 'package:adaptive_dialog/adaptive_dialog.dart';
import 'package:flustars/flustars.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';

import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart';

import 'package:smart_freezer/core/model/product_model.dart';
import 'package:smart_freezer/core/resources/app_config.dart';
import 'package:smart_freezer/core/resources/icon_names.dart';
import 'package:smart_freezer/core/resources/routers.dart';
import 'package:smart_freezer/core/service/api/app_api.dart';
import 'package:smart_freezer/core/service/service/result_data.dart';
import 'package:smart_freezer/core/utils/local_storage.dart';
import 'package:smart_freezer/core/utils/logs.dart';
import 'package:smart_freezer/core/utils/tr_extension.dart';
import 'package:smart_freezer/core/view/date_picker.dart';
import 'package:smart_freezer/core/view/update_location.dart';
import 'package:smart_freezer/core/view/update_time.dart';
import 'package:smart_freezer/generated/locale_keys.g.dart';

import '../../../core/utils/color_util.dart';

class DeviceSetting extends StatefulWidget {
  const DeviceSetting({Key? key}) : super(key: key);

  @override
  State<DeviceSetting> createState() => _DeviceSettingState();
}

class _DeviceSettingState extends State<DeviceSetting> {

  final _productIdList = Get.arguments as List;
  String _productId = "";
  ProductModel _productModel = ProductModel();

  List _dataList = [
    // {"title": "", "content": ""},
    // {"title": LocaleKeys.device_info_upload_sequence.trc(), "content": "0min"},

    {"title": LocaleKeys.device_info_device_name.trc(), "content": ""},
    {"title": LocaleKeys.device_info_device_address.trc(), "content": ""},
    {"title": LocaleKeys.device_info_device_jingxiao.trc(), "content": ""},
    {"title": "", "content": ""},
    {"title": LocaleKeys.device_info_device_share.trc(), "content": ""},
  ];

  List<Map<String, String>> _floorList = [];

  bool isDarkMode = LocalStorage.getThemeMode() == 1;

  // 非厨师, 限制参数查看和修改.
  bool isNotChushi = LocalStorage.getRole() != "1";
  // 工程经理, 允许工程经理查看和修改经销商. 新增技术员.
  bool isProject = LocalStorage.getRole() == "3" || LocalStorage.getRole() == "2";

  @override
  void initState() {
    super.initState();

    if(isNotChushi) {
      _dataList.insertAll(
          0,
          [
            {"title": LocaleKeys.device_info_params_setting.trc(), "content": ""},
            {"title": "", "content": ""},
            {"title": LocaleKeys.device_info_info_setting.trc(), "content": ""},
          ],
      );
    }

    _productId = _productIdList.first;

    _getDeviceInfo();
  }

  @override
  Widget build(BuildContext context) {
    logs("设备参数");

    return Scaffold(
      appBar: AppBar(
        // backgroundColor: Colors.white,
        elevation: 1,
        leadingWidth: 50,
        leading: InkWell(
          onTap: () {
            Get.back();
          },
          child: Container(
            padding: EdgeInsets.fromLTRB(0, 9, 0, 9),
            child: Icon(Icons.arrow_back_ios_rounded),
          ),
        ),
        title: Text(_productIdList.length == 1 ? LocaleKeys.device_info_device_setting.trc() : LocaleKeys.set_up_control_select.trc(),),
        centerTitle: true,
      ),
      body: Container(
        width: MainCommon.screenWidth,
        padding: EdgeInsets.fromLTRB(0, 20, 0, 0),
        color: isDarkMode ? Colors.black : MainCommon.bgGreyColor,
        child: ListView.builder(
            itemCount: _dataList.length,
            itemBuilder: (context, index){
              final data = _dataList[index];
              final title = data["title"].toString();
              final content = data["content"];

              return title.isNotEmpty ? InkWell(
                onTap: () async {
                  if(title == LocaleKeys.device_info_device_name.trc()){  // 设备名称
                    final text = await showTextInputDialog(
                      context: context,
                      textFields: [
                        DialogTextField(initialText: _productModel.name),
                      ],
                      title: LocaleKeys.device_info_edit_name.trc(),

                      builder: (context, child) => Theme(
                        data: ThemeData(
                            primarySwatch: createMaterialColor(isDarkMode ? Colors.white : Colors.black),
                            dialogBackgroundColor: isDarkMode ? MainCommon.darkBlueMaterialColor : Colors.white,
                            colorScheme: ColorScheme(
                              primary: isDarkMode ? Colors.white : Colors.black, // 文字颜色
                              primaryVariant: Colors.white,
                              secondary: Colors.green,
                              background: Colors.white,
                              error: Colors.red,
                              brightness: isDarkMode ? Brightness.dark : Brightness.light,    /// 最最关键
                              onBackground: Colors.pink,
                              secondaryVariant: Colors.white,
                              onError: Colors.yellow,
                              onPrimary: Colors.red, //顶部栏字体颜色
                              onSecondary: Colors.black,
                              onSurface: Colors.white,   // 导航栏字体颜色, 返回按钮颜色
                              surface: MainCommon.darkBlueMaterialColor,  // 导航栏背景颜色

                            )
                        ),
                        child: child,
                      ),

                    );
                    if(text != null) {
                      _productIdList.forEach((ele) {
                        _updateDeviceName(text.first, ele);
                      });

                    }
                  }else if(title == LocaleKeys.device_info_device_jingxiao.trc()) {
                    final text = await showTextInputDialog(
                      context: context,
                      textFields: [
                        DialogTextField(initialText: _productModel.agencyName),
                      ],
                      title: "${LocaleKeys.device_info_edit.trc()} ${LocaleKeys.device_info_device_jingxiao.trc().toLowerCase()}",
                      builder: (context, child) => Theme(
                        data: ThemeData(
                          primarySwatch: createMaterialColor(isDarkMode ? Colors.white : Colors.black),
                          dialogBackgroundColor: isDarkMode ? MainCommon.darkBlueMaterialColor : Colors.white,
                            colorScheme: ColorScheme(
                              primary: isDarkMode ? Colors.white : Colors.black, // 文字颜色
                              primaryVariant: Colors.white,
                              secondary: Colors.green,
                              background: Colors.white,
                              error: Colors.red,
                              brightness: isDarkMode ? Brightness.dark : Brightness.light,    /// 最最关键
                              onBackground: Colors.pink,
                              secondaryVariant: Colors.white,
                              onError: Colors.yellow,
                              onPrimary: Colors.red, //顶部栏字体颜色
                              onSecondary: Colors.black,
                              onSurface: Colors.white,   // 导航栏字体颜色, 返回按钮颜色
                              surface: MainCommon.darkBlueMaterialColor,  // 导航栏背景颜色
                            )
                        ),
                        child: child,
                      ),
                    );
                    if(text != null) {
                      _productIdList.forEach((ele) {
                        _updateAgencyName(text.first, ele);
                      });
                    }
                  }else if(title == LocaleKeys.device_info_device_address.trc()) {
                    _getFloorInfo();
                  }else if(title == LocaleKeys.device_info_upload_sequence.trc()){
                    showModalBottomSheet<void>(
                        context: context,
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.only(
                            topLeft: Radius.circular(20),
                            topRight: Radius.circular(20),
                          ),
                        ),
                        builder: (BuildContext context) {
                          return UpdateTime(
                            endValue: DateTime.now().year,
                            selectedValue: "",
                            onSelectedValue: (String value) {
                              Navigator.pop(context);
                              logs("$value");
                            },
                          );
                        });
                  }else if(title == LocaleKeys.device_info_device_share.trc()) {
                    Get.toNamed(LCRouter.device_share_share, arguments: _productModel);
                  }

                  if(index == 0) {
                    Get.toNamed(LCRouter.device_setting_params, arguments: _productIdList);
                  }
                },
                child: Container(
                  color: isDarkMode ? MainCommon.darkBlueMaterialColor : Colors.white,
                  height: isNotChushi ? (index == 2 ? 40 : 50) : 50,
                  padding: EdgeInsets.fromLTRB(20, 0, 20, 0),
                  child: Column(
                    children: [
                      Container(
                        height: isNotChushi ? (index == 2 ? 39 : 49) : 49,
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Text(title, style: TextStyle(fontSize: isNotChushi ? (index == 2 ? 16 : 16) : 16),),  // 信息设置
                            Row(
                              children: [
                                Text(content, style: TextStyle(fontSize: 15, color: Colors.grey),),
                                isNotChushi ? (index == 2 ? Container() : Icon(Icons.chevron_right, color: Colors.grey.shade400,)) :
                                      Icon(Icons.chevron_right, color: Colors.grey.shade400,),
                              ],
                            ),

                          ],
                        ),
                      ),
                      Divider(
                        height: 1,
                        indent: 5,
                        endIndent: 5,
                      ),
                    ],
                  ),
                ),
              ) : SizedBox(height: 10,);
        }),
      ),
    );
  }

  // 获取设备数据
  _getDeviceInfo() async {
    final params = {"productId": "${_productId}"};
    ResultData data = await AppApi.getInstance().getProductInfo(params);
    if(data.code == 0){
      _productModel = ProductModel.fromJson(data.data);

      _dataList = [
        // {"title": "", "content": ""},
        // {"title": LocaleKeys.device_info_upload_sequence.trc(), "content": "${_productModel.uploadFrequency}min"},

        {"title": LocaleKeys.device_info_device_name.trc(), "content": _productModel.name},
        {"title": LocaleKeys.device_info_device_address.trc(), "content": "${_productModel.hallName} ${_productModel.floorName}"},
        {"title": "", "content": ""},
        {"title": LocaleKeys.device_info_device_share.trc(), "content": ""},  // ${_productModel.shareCount}人 不显示分享人数
      ];
      setState(() {});

      if(isNotChushi) {  // 非厨师
        _dataList.insertAll(
            0,
            [
              {"title": LocaleKeys.device_info_params_setting.trc(), "content": ""},
              {"title": "", "content": ""},
              {"title": LocaleKeys.device_info_info_setting.trc(), "content": ""},
            ]
        );
      }

      if(isProject){  // 项目经理
        _dataList.insertAll(isNotChushi ? 3 + 2 : 2, [
          {"title": LocaleKeys.device_info_device_jingxiao.trc(), "content": "${_productModel.agencyName}"},
        ]);
      }


    }else {
      SmartDialog.showToast(data.msg);
    }
  }

  // 修改设备名称
  _updateDeviceName(String name, String productId) async {
    final params = {"productId": productId, "name": name};
    ResultData data = await AppApi.getInstance().updateProductName(params);
    if(data.code == 0){
      _getDeviceInfo();
    }else {
      SmartDialog.showToast(data.msg);
    }
  }

  // 修改经销商名称
  _updateAgencyName(String name, String productId) async {
    final params = {"productId": productId, "agencyName": name};
    ResultData data = await AppApi.getInstance().updateAgencyName(params);
    if(data.code == 0){
      _getDeviceInfo();
    }else {
      SmartDialog.showToast(data.msg);
    }
  }

  // 获取楼层数据
  _getFloorInfo() async {
    ResultData data = await AppApi.getInstance().getFloorInfo();
    if(data.code == 0){
      if(data.data == null) return;

      final list = data.data as List;
      logs("_floorList2: ${data.data}");
      _floorList = list.map((e) => {"id": e["id"].toString(), "name": e["name"].toString()}).toList();
      setState(() {});

      logs("_floorList: ${data.data}");

      showModalBottomSheet<void>(
          context: context,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.only(
              topLeft: Radius.circular(20),
              topRight: Radius.circular(20),
            ),
          ),
          builder: (BuildContext context) {
            return UpdateLocation(
              yearList: _floorList,
              selectedValue: "",
              onSelectedValue: (String value) {
                Navigator.pop(context);
                logs("$value");

                // 更新设备位置
                _productIdList.forEach((ele) {
                  _updateLocation(value, ele);
                });

              },
            );
          });

    }else {
      SmartDialog.showToast(data.msg);
    }
  }

  _updateLocation(String hallId, String productId) async {
    final params = {"productId": productId, "hallId": hallId};
    ResultData data = await AppApi.getInstance().updateLocation(params);
    if(data.code == 0){
      _getDeviceInfo();
    }else{
      SmartDialog.showToast(data.msg);
    }
  }



}
